
package com.tnl.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.tnl.app.dao.*;
import com.tnl.app.entity.*;
import com.tnl.app.service.IEmployeeService;
import com.tnl.app.service.IPersonService;
import com.tnl.app.service.IRecommendService;
import com.tnl.app.vo.PageVo;
import com.tnl.app.vo.TimePart;
import com.tnl.app.vo.YuYueVo;
import com.tnl.base.Const;
import com.tnl.base.web.JsonController;
import com.tnl.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/new")
public class NewController extends JsonController {

    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private EmployeeDAO employeeDAO;
    @Autowired
    private PersonDAO personDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private HunterDescDAO hunterDescDAO;
    @Autowired
    private EvaluateDAO evaluateDAO;
    @Autowired
    private OrderDescDAO orderDescDAO;
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private ArticleDAO articleDAO;
    @Autowired
    private WxAppUserDAO wxAppUserDAO;
    @Autowired
    private UserCouponDAO userCouponDAO;
    @Autowired
    private MyCalendarDAO myCalendarDAO;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IRecommendService recommendService;
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 顾问列表
     *
     * @param response
     */
    @RequestMapping(value = "getHunterList")
    public void getHunterList(Integer page, Integer size, HttpServletResponse response) {
        //获取总的数据条数
        int totalNum = hunterDAO.getTotalNumForHunterList();
        int pageNum = getPageNum(totalNum, size);
        int offset = (page - 1) * size;

        List<Hunter> list = hunterDAO.getHunterList(offset, size);
        for (Hunter hunter : list) {
            hunter.setImageUrl(hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
            List<OrderDesc> ordesc = hunterDescDAO.getALL(hunter.getId());
            if (ordesc.size() > 0) {
                for (OrderDesc orderDesc : ordesc) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", orderDesc.getId());
                    map.put("tag", orderDesc.getTag());
                    map.put("name", orderDesc.getName());
                    hunter.getDescList().add(map);
                }
            }
        }
        this.successJson(new PageVo(list, pageNum), "咨询顾问", response);
    }

    /**
     * 顾问详情
     *
     * @param response
     * @param hunterid
     */
    @RequestMapping(value = "hunterdetail")
    public void getHunterDetail(HttpServletResponse response, Integer hunterid) {
        Hunter hunter = hunterDAO.getById(hunterid);
        hunter.setImageUrl(hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
        List<OrderDesc> orderDescList = hunterDescDAO.getHunterByOrdesc(hunterid);
        List<String> orderDesc = orderDescList.stream().map(OrderDesc::getTag).collect(Collectors.toList());
        hunter.setOrderDesc(orderDesc);
        this.successJson(hunter, "顾问详情", response);
    }

    /**
     * 咨询项目-跳槽\升职\加薪
     *
     * @param response
     */
    @RequestMapping(value = "getOrderDescList")
    public void getOrderDescList(HttpServletResponse response, Integer hunterid) {
        JSONObject json = new JSONObject();
        List<OrderDesc> ordesc = hunterDescDAO.getHunterByOrdesc(hunterid);
        if (ordesc.size() == 5) {
            json.put("change", orderDescDAO.getByTag(hunterid, ordesc.get(0).getTag()));
            json.put("interview", orderDescDAO.getByTag(hunterid, ordesc.get(1).getTag()));
            json.put("up", orderDescDAO.getByTag(hunterid, ordesc.get(2).getTag()));
            json.put("salary", orderDescDAO.getByTag(hunterid, ordesc.get(3).getTag()));
            json.put("leave", orderDescDAO.getByTag(hunterid, ordesc.get(4).getTag()));
        } else if (ordesc.size() == 4) {
            json.put("change", orderDescDAO.getByTag(hunterid, ordesc.get(0).getTag()));
            json.put("interview", orderDescDAO.getByTag(hunterid, ordesc.get(1).getTag()));
            json.put("up", orderDescDAO.getByTag(hunterid, ordesc.get(2).getTag()));
            json.put("salary", orderDescDAO.getByTag(hunterid, ordesc.get(3).getTag()));
        } else if (ordesc.size() == 3) {
            json.put("change", orderDescDAO.getByTag(hunterid, ordesc.get(0).getTag()));
            json.put("interview", orderDescDAO.getByTag(hunterid, ordesc.get(1).getTag()));
            json.put("up", orderDescDAO.getByTag(hunterid, ordesc.get(2).getTag()));
        } else if (ordesc.size() == 2) {
            json.put("change", orderDescDAO.getByTag(hunterid, ordesc.get(0).getTag()));
            json.put("interview", orderDescDAO.getByTag(hunterid, ordesc.get(1).getTag()));
        } else if (ordesc.size() == 1) {
            json.put("change", orderDescDAO.getByTag(hunterid, ordesc.get(0).getTag()));
        }
        this.successJson(json, String.valueOf(ordesc.size()), response);
    }

    /**
     * 根据Id咨询项目
     *
     * @param response
     */
    @RequestMapping(value = "getOrderDescId")
    public void getOrderDescId(HttpServletResponse response, Integer oritemid) {
        OrderDesc item = orderDescDAO.getById(oritemid);
        this.successJson(item, "根据id咨询项目", response);

    }

    @RequestMapping(value = "getIdByOrdercode")
    public void getIdByOrdercode(HttpServletResponse response, String ordercode) {
        Order order = orderDAO.getOrderByCode(ordercode);
        OrderDesc odes = orderDescDAO.getById(order.getOrdescId());
        if (odes != null) {
        	order.setTag(odes.getTag());
        }
        this.successJson(order, "根据id咨询项目", response);

    }

    /**
     * 当前用户优惠券-放用户empId
     *
     * @param response
     */
    @RequestMapping(value = "getUserCoupon")
    public void getUserCoupon(HttpServletResponse response, String unionid, String spec) {
        Employee emp = employeeDAO.getEmpByUnionid(unionid);
        List<UserCoupon> list = null;
        if (emp != null) {
            list = userCouponDAO.getById(emp.getEmpid(), spec);
        }
        //List<UserCoupon> list=userCouponDAO.getALL();
        this.successJson(list, "当前用户可用的优惠券", response);
    }

    /**
     * 针对于购买咨询服务项目用于给咨询评分
     *
     * @param response
     * @param openid   状态值说明：
     *                 status=0 前台不显示
     *                 status=1 前台显示
     *                 anonymous=0 表示公开
     *                 anonymous=1 表示匿名，在页面上展示用（*）
     *                 --卖家评价状态类似
     *                 buyerEvalStatus=0 主动评价
     *                 buyerEvalStatus=1 系统默认/修改评价
     */
    @RequestMapping(value = "createEvaluate")
    public void createEvaluate(HttpServletResponse response, String openid, String hunterid, String huntername,
                               String orderId, String nickName, String orderdescIds, Integer buyerEvalScore,
                               String buyerEvalContent, Integer anonymous) {
        Evaluate eva = new Evaluate();
        eva.setOrderId(orderId);
        eva.setBuyerId(openid);
        eva.setBuyerName(nickName);
        eva.setHunterId(hunterid);
        eva.setHunterName(huntername);
        eva.setBuyerEvalScore(buyerEvalScore);
        eva.setBuyerEvalTime(DateUtil.currentTime());
        eva.setBuyerEvalContent(buyerEvalContent);
        eva.setOrderdescIds(orderdescIds);
        if (buyerEvalContent != null) {
            eva.setBuyerEvalStatus(0);
        } else {
            eva.setBuyerEvalStatus(1);
        }
        if (buyerEvalScore <= 3) {//三星以及三星一下不会立即显示
            eva.setStatus(0);
        } else {
            eva.setStatus(1);
        }
        if (anonymous != 1 || anonymous != null) {
            eva.setAnonymous(anonymous);
        } else {
            eva.setAnonymous(0);
        }

        int result = evaluateDAO.save(eva);
        if (result > 0) {
            orderDAO.updateStatus(6, Integer.parseInt(orderId));
        }
        this.successJson(result, "评论成功", response);
    }

    /**
     * 查询咨询师评价信息
     */
    @RequestMapping(value = "selectByEvaId")
    public void selectByEvaluateId(HttpServletResponse response, Integer hunterid) {
        List<Evaluate> evalist = evaluateDAO.getHunterByEva(hunterid);
        for (Evaluate evaluate : evalist) {
            WxAppUser user = wxAppUserDAO.getByOpenId(evaluate.getBuyerId());
            if (user != null) {
                evaluate.setBuyerName(user.getNickname() != null ? user.getNickname() : "匿名");
                evaluate.setBuyHeadImg(user.getAvatar());
            }
        }
        this.successJson(evalist, "此咨询师评论列表", response);

    }

    /**
     * 根据订单查询评价信息
     */
    @RequestMapping(value = "selectEvaByOrderId")
    public void selectEvaByOrderId(HttpServletResponse response, Long orderId) {
        Evaluate eva = evaluateDAO.getByOrderId(orderId);
        this.successJson(eva, "根据订单查询评价信息", response);

    }

    /**
     * 查询咨询师文章信息
     */
    @RequestMapping(value = "selectByArticle")
    public void selectByArticle(HttpServletResponse response, Integer hunterid, Integer pageSize) {
        List<ArticleInfo> arts = articleDAO.getHunterByArts(hunterid, 0, pageSize);
        this.successJson(arts, "此咨询师TOP文章列表", response);
    }

    @RequestMapping(value = "getHunterArticles")
    public void getHunterArticles(HttpServletResponse response, Integer hunterid) {
        List<ArticleInfo> arts = articleDAO.getHunterArticles(hunterid);
        this.successJson(arts, "此咨询师所有文章列表", response);
    }

    /**
     * 咨询师回复
     */
    @RequestMapping(value = "replyEvaluate")
    public void replyEvaluate(HttpServletResponse response, String replyContent, Integer evaid) {
        int result = evaluateDAO.updateEvaluate(replyContent, evaid);
        this.successJson(result, "咨询师回复成功", response);
    }

    /**
     * 我的评价
     */
    @RequestMapping(value = "myassess")
    public void myAssess(HttpServletResponse response, String openid) {
        List<Evaluate> list = evaluateDAO.getBuyerEvaId(openid);
        for (Evaluate evaluate : list) {
            Hunter hunter = hunterDAO.getById(Integer.parseInt(evaluate.getHunterId()));
            if (hunter != null) {
                hunter.setImageUrl(hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                if (hunter.getDomainName1() != null) {
                    evaluate.setDomainName1(hunter.getDomainName1());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain1());
                    evaluate.setDomainName1(domain.getName());
                }
                if (hunter.getDomainName2() != null) {
                    evaluate.setDomainName2(hunter.getDomainName2());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain2());
                    evaluate.setDomainName2(domain.getName());
                }
                if (hunter.getDomainName3() != null) {
                    evaluate.setDomainName3(hunter.getDomainName3());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain3());
                    evaluate.setDomainName3(domain.getName());
                }
                if (hunter.getCityName() != null) {
                    evaluate.setCityName(hunter.getCityName());
                } else {
                    City city = cityDAO.getById(hunter.getCityId());
                    evaluate.setCityName(city.getName());
                }
                evaluate.setWorkage(hunter.getWorkage());
            }
        }
        this.successJson(list, "我的评价", response);
    }

    /**
     * 顾问预约时间
     * 2018-7-20
     */
    @RequestMapping(value = "getOrderTimeId")
    public void getOrderTimes(HttpServletResponse response, String proTimeId) {
        MyCalendar myCalendar = myCalendarDAO.getById(proTimeId);
        TimePart tmp = new TimePart(myCalendar.getId(), myCalendar.getStarttime().substring(0, 11), myCalendar.getStarttime().substring(11, 16), myCalendar.getEndtime().substring(11, 16));
        this.successJson(tmp, "用户预约时间", response);
    }

    @RequestMapping(value = "getOrderTime")
    private void testYuYue(HttpServletResponse response, Integer hunterid) {
        int monthtmp = 0;

        Date currDay = new Date();
        int tempNum = DateUtil.getWeekOfDate(currDay);
        Date firstDay = null;
        if (tempNum == 0) {
            //表示现在是周日，那么第一个时间就是现在
            firstDay = currDay;
        } else {
            firstDay = DateUtil.dateAddDay(-tempNum, currDay);
        }

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        int tmpMonth = firstDay.getMonth();
        //计算周天开始的第一天
        List<YuYueVo> dataList = new ArrayList<YuYueVo>();
        YuYueVo first = new YuYueVo();
        first.setDate(format.format(firstDay));
        cal.setTime(firstDay);
        first.setDay(cal.get(Calendar.DAY_OF_MONTH));
        first.setMonth(cal.get(Calendar.MONTH));
        first.setIs_display(1);
        first.setStatus("已满");
        dataList.add(first);


        for (int i = 1; i < 21; i++) {
            Date time = DateUtil.dateAddDay(i, firstDay);
            cal.setTime(time);
            YuYueVo vo = new YuYueVo();
            vo.setDate(format.format(time));
            vo.setDay(cal.get(Calendar.DAY_OF_MONTH));
            vo.setMonth(cal.get(Calendar.MONTH));
            if (tmpMonth != vo.getMonth() && monthtmp == 0) {
                vo.setIs_display(1);
                monthtmp = 1;
            }
            List<MyCalendar> myCalendars = myCalendarDAO.getTimePart(hunterid, format.format(time), 0);
            List<MyCalendar> booked = myCalendarDAO.getTimePart(hunterid, format.format(time), 1);
            if (myCalendars.size() != 0) {
                List<TimePart> tmpTime = new ArrayList<TimePart>();
                for (MyCalendar myCalendar : myCalendars) {
                    if (DateUtil.compareDate(myCalendar.getStarttime(), DateUtil.currentTime()) == 1) {
                        vo.setStatus("未满");
                        tmpTime.add(new TimePart(myCalendar.getId(), myCalendar.getStarttime().substring(11, 16), myCalendar.getEndtime().substring(11, 16)));
                        vo.setTimeList(tmpTime);
                    } else {
                        vo.setStatus("已满");
                    }
                }
            } else if (booked.size() != 0) {
                vo.setStatus("已满");
            } else {
                vo.setStatus("未开放");
            }
            dataList.add(vo);
        }
        this.successJson(dataList, "顾问预约时间", response);
    }

    @RequestMapping(value="tset")
	public void test() {
		List<JobDesc> list = jobDAO.getListNoCompanyId();
		List<JobDesc> jobs = new ArrayList<JobDesc>();
		for(JobDesc j : list) {
			City city = cityDAO.getByName(j.getLocation());
			if (city !=null) {
				j.setCityId(city.getId());
			}

			Company com = companyDAO.getByName(j.getJobContact());
			if (com !=null) {
				j.setCompanyId(com.getId());
			}
			
			Domain domain = domainDAO.getByName(j.getGroupMember());
			if (domain !=null) {
				j.setDomainID(domain.getId());
				j.setDomainName(domain.getName());
			}
			jobs.add(j);
		}
		jobDAO.updateBatch(jobs);
	}
}
